#!/usr/bin/python3
# -*- coding: utf-8 -*-

from requests import get as http_get

from ikanda.core.command import open_for_write, Resource, CallbackLogger

_DOWNLOAD_CHUNK_SIZE = 4 * 1024


class HttpResource(Resource):
    def close(
            self,
            callback: CallbackLogger
    ):
        pass

    @staticmethod
    def __get(
            url: str,
            params: dict
    ):
        rsp = http_get(url, params=params)
        if rsp.ok:
            return rsp
        else:
            raise TypeError('cannot get json, cause: ' + rsp.text)

    def get_str(
            self,
            url: str,
            params: dict = None,
            **kwargs
    ) -> str:
        if params is None:
            params = dict()
        if kwargs:
            params.update(kwargs)

        return self.__get(url, params=params).text

    def get_int(
            self,
            url: str,
            params: dict = None,
            **kwargs
    ) -> int:
        if params is None:
            params = dict()
        if kwargs:
            params.update(kwargs)

        s = self.__get(url, params=params).text.strip()
        return int(s) if s else None

    def get_bool(
            self,
            url: str,
            params: dict = None,
            **kwargs
    ) -> bool:
        if params is None:
            params = dict()
        if kwargs:
            params.update(kwargs)

        s = self.__get(url, params=params).text.strip().lower()
        if s == 'yes' or s == 'true' or s == 'on' or s == 't' or s == 'y' or s == '1':
            return True
        elif s == 'no' or s == 'false' or s == 'off' or s == 'f' or s == 'n' or s == '0':
            return False
        else:
            raise ValueError('unknown bool: ' + s[:5])

    def get_json(
            self,
            url: str,
            params: dict = None,
            **kwargs
    ):
        if params is None:
            params = dict()
        if kwargs:
            params.update(kwargs)

        return self.__get(url, params=params).json()

    @staticmethod
    def download(
            url: str,
            params: dict = None,
            file=None,
            **kwargs
    ):
        if params is None:
            params = dict()
        if kwargs:
            params.update(kwargs)

        rsp = http_get(url, params=params)
        with open_for_write(file) as df:
            for chunk in rsp.iter_content(chunk_size=_DOWNLOAD_CHUNK_SIZE):
                if chunk:  # filter out keep-alive new chunks
                    df.write(chunk)
